package com.example.musicplayer

import android.app.Service
import android.content.Intent
import android.content.res.AssetFileDescriptor
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Binder
import android.os.IBinder
import com.example.musicplayer.MainActivity.Companion.ACTION_UPDATE_INFO
import java.io.File
import java.io.RandomAccessFile
import java.nio.charset.Charset


class MusicService : Service() {

    var index = 0
    var mMediaPlayer: MediaPlayer? = null
    var songUrls = arrayOf(
//            "https://github.com/boyla/Music_JayZhou/raw/master/%E4%B8%83%E9%87%8C%E9%A6%99/%E5%91%A8%E6%9D%B0%E4%BC%A6%20-%20%E6%90%81%E6%B5%85.mp3",
//            "https://github.com/boyla/Music_JayZhou/raw/master/%E4%B8%83%E9%87%8C%E9%A6%99/%E5%91%A8%E6%9D%B0%E4%BC%A6%20-%20%E4%B8%83%E9%87%8C%E9%A6%99.mp3",
//            "https://github.com/boyla/Music_JayZhou/raw/master/%E4%BE%9D%E7%84%B6%E8%8C%83%E7%89%B9%E8%A5%BF/%E5%91%A8%E6%9D%B0%E4%BC%A6%E3%80%81%E8%B4%B9%E7%8E%89%E6%B8%85%20-%20%E5%8D%83%E9%87%8C%E4%B9%8B%E5%A4%96.mp3"
//
            R.raw.jay,
            R.raw.jay1,
            R.raw.jay2
    )
    var musicController: MusiceController? = null

    override fun onCreate() {
        super.onCreate()
        mMediaPlayer = MediaPlayer.create(this, songUrls[index])
//        mMediaPlayer = MediaPlayer.create(this, Uri.parse(songUrls[index]))
        mMediaPlayer?.setAudioStreamType(AudioManager.STREAM_MUSIC)//设置音频类型
//        mMediaPlayer?.isLooping = true
    }

    override fun onBind(intent: Intent?): IBinder? {
        musicController = MusiceController()
        return musicController
    }

    override fun onDestroy() {
        if (mMediaPlayer?.isPlaying == true) {
            mMediaPlayer?.stop()
        }
        mMediaPlayer?.release()
        mMediaPlayer = null
        super.onDestroy()
    }

    inner class MusiceController : Binder() {

        fun play() {
            innerPlay()
        }

        fun pause() {
            mMediaPlayer?.pause()
        }

        fun getDuration(): Long {
            return (mMediaPlayer?.duration ?: 1).toLong()
        }

        fun getPosition(): Long {
            return (mMediaPlayer?.currentPosition ?: 0).toLong()
        }

        fun seekTo(position: Int) {
            mMediaPlayer?.seekTo(position)
        }

        fun isPlaying(): Boolean {
            return mMediaPlayer?.isPlaying == true
        }

        fun next() {
            if (mMediaPlayer?.isPlaying == true) {
                mMediaPlayer?.stop()
            }
            mMediaPlayer?.release()

            index = (index + 1) % songUrls.size
//            mMediaPlayer?.setDataSource(songUrls[index])
            mMediaPlayer = MediaPlayer.create(this@MusicService, songUrls[index])
            innerPlay()
        }

        fun previous() {
            if (mMediaPlayer?.isPlaying == true) {
                mMediaPlayer?.stop()
            }
            mMediaPlayer?.release()

            index = (index + songUrls.size - 1) % songUrls.size
//            mMediaPlayer?.setDataSource(songUrls[index])
            mMediaPlayer = MediaPlayer.create(this@MusicService, songUrls[index])
            innerPlay()
        }

        fun innerPlay() {
            mMediaPlayer?.start()
            mMediaPlayer?.setOnCompletionListener { if (mMediaPlayer?.isLooping == false) musicController?.next() }
            Thread { getInfo() }.start()
        }

        fun getInfo() {
            /**
            读取MP3文件最后128 Byte, 并分别取出各个信息：
            将文件指针偏移量移动到文件长度倒数128位；
            判断标签头"TAG"是否存在；
            读取TAG_V1中的各个内容；
            关闭文件
             */
            val buf = ByteArray(128)
            try {
                val afd: AssetFileDescriptor = this@MusicService.getResources().openRawResourceFd(songUrls[index])
                var afdLen = afd.length

                val inputStream = resources.openRawResource(songUrls[index])
                inputStream.skip(afdLen - 128)
                inputStream.read(buf)
                inputStream.close()
            } catch (e: Exception) {
                e.printStackTrace();
            }

            var tag = String(buf, 0, 3)
            var ret = "unknown - unknown"
            if ("TAG".equals(tag, true)) {//标签头是否存在
                var cs = "GB2312"

                //5.获得TAG_V1中的各个内容
                val SongName = String(buf, 3, 30, Charset.forName(cs)).trim { it <= ' ' } //歌曲名称


                val Artist = String(buf, 33, 30, Charset.forName(cs)).trim { it <= ' ' } //歌手名字


//                val Album = String(buf, 63, 30, Charset.forName(cs)).trim { it <= ' ' } //专辑名称


//                val Year = String(buf, 93, 4, Charset.forName(cs)).trim { it <= ' ' } //出品年份


//                val Comment = String(buf, 97, 28, Charset.forName(cs)).trim { it <= ' ' } //备注信息

                ret = SongName + " - " + Artist

            }

//            var cs = "UTF-8"

            MainActivity.info = ret

            var intent = Intent(ACTION_UPDATE_INFO)
            this@MusicService.sendBroadcast(intent)
        }
    }
}